package cn.lzm.basic.controller;

import cn.lzm.basic.util.AjaxResult;
import cn.lzm.basic.util.FastdfsUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RequestMapping("/fastdfs")
@RestController
public class FastdfsController {
    @PostMapping
    public AjaxResult upload(@RequestPart(value = "file",required = true)MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            String suffix = FilenameUtils.getExtension(filename);
            String path = FastdfsUtil.upload(file.getBytes(), suffix);
            return AjaxResult.me().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请重试！");
        }

    }

    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "path", required = true) String path){
        try {
            String pathTmp = path.substring(1);
            String grouName = pathTmp.substring(0, pathTmp.indexOf("/"));
            String remotePath = pathTmp.substring(pathTmp.indexOf("/") + 1);
            FastdfsUtil.delete(grouName,remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请重试！");
        }
    }
}
